import Taro from "@tarojs/taro";
export type cartListType = {
  id: string;
  picture: string;
  title: string;
  price: number;
  num: number;
  count: number;
  onSelect: boolean;
  stockId: number;
};

export default {
  namespace: "cart",
  state: [],

  effects: {},

  reducers: {
    // state 当前状态
    addCartList(state: cartListType[], { payload }) {
      if (payload.length != 0) {
        let flag = false;
        const temp = state.map(element => {
          if (element.id == payload.id) {
            element.count += 1;

            flag = true;
            return element;
          } else {
            return element;
          }
        });

        if (flag) {
          Taro.setStorageSync("cart", JSON.stringify([...temp]));
          return [...temp];
        }
        payload.count = 1;
        Taro.setStorageSync("cart", JSON.stringify([...state, payload]));
        return [...state, payload];
      } else {
        return state;
      }
    },
    reduceNumber(state, { payload }) {
      const { id, num } = payload;

      const temp = state.map(i => {
        if (i.id == id) {
          i.count = num;
        }

        return i;
      });

      Taro.setStorageSync("cart", JSON.stringify([...temp]));
      return [...temp];
    },

    pushData(state, { payload }) {
      const { id } = payload;
      const list = [];
      state.map(item => {
        if (item.id != id) {
          list.push(item);
        }
      });
      Taro.setStorageSync("cart", JSON.stringify([...list]));
      return [...list];
    },

    initData(state, { payload }) {
      return payload;
    }
  },
  subscriptions: {
    initData({ dispatch }) {
      let localStoreData = Taro.getStorageSync("cart");

      if (!localStoreData) {
        localStoreData = "[]";
      }

      dispatch({
        type: "cart/initData",
        payload: JSON.parse(localStoreData)
      });
    }
  }
};
